'use strict';

    var fakeDragStack = [];
    var workspace = null;

    function start() {
      var soundsEnabled = false;

      // Setup blocks
      // Parse the URL arguments.
      //var rtl =  'ltr';
      var toolbox = getToolboxElement();
      var side = 'end';

      //document.forms.options.elements.side.value = side;

      workspace = Blockly.inject('blocklyDiv', {
        comments: false,
        disable: false,
        collapse: false,
        media: 'media/',
        readOnly: false,
        scrollbars: true,
        toolbox: toolbox,
        trashcan: true,
        horizontalLayout: true,
        toolboxPosition: side,
        sounds: soundsEnabled,
        grid: {spacing: 16,
          length: 1,
          colour: '#2C344A',
          snap: false
        },
        zoom: {
          controls: true,
          wheel: true,
          startScale: 0.6,
          maxScale: 4,
          minScale: 0.25,
          scaleSpeed: 1.1
        },
        colours: {
          fieldShadow: 'rgba(255, 255, 255, 0.3)',
          dragShadowOpacity: 0.6
        }
      });
      workspace.setScale(0.6);
      workspace.addChangeListener(onNumChange);

    }

    function onNumChange(event) {
      if (event.type == Blockly.Events.CHANGE) {

        //workspace.removeChangeListener(onFirstComment
        var block  = workspace.getBlockById(event.blockId);
        //console.log(event.element +' name= '+ event.name);
        var field = block.getField('NUM');
        var newValue = event.newValue;
        var oldValue = event.oldValue;
        if(newValue&& newValue.length>2){
          field.text_ = oldValue;
          //event.preventDefault();
          return;
        }


        if(field.text_){
          field.textElement_.textContent=field.text_;
        }
      }
    }


    function getToolboxElement() {
      return document.getElementById('toolboxDiv');
    }

    function toXml(key) {
      //var output = document.getElementById('importExport');
      var xml = Blockly.Xml.workspaceToDom(workspace);
      var value  = Blockly.Xml.domToPrettyText(xml)
      //output.value = Blockly.Xml.domToPrettyText(xml);
      if(key){
        return value;
      }
      //Toaster.postMessage(value);

      //console.log(xml);
      //output.focus();
      //output.select();
      //taChange();
    }

    function fromXml(input) {
      //var input = document.getElementById('importExport
      //var input = '<xml><variables></variables><block type="control_forever" id="4Rmd8eEg(d`B2[snvIq^" x="42" y="55"></block></xml>';
      //workspace.clear();
      var xml = Blockly.Xml.textToDom(input);
      Blockly.Xml.clearWorkspaceAndLoadFromXml(xml,workspace);
      //Blockly.Xml.domToWorkspace(workspace, xml);
      //taChange();
    }

    function fromMyXml(input) {
      //var input = document.getElementById('importExport
      //var input = '<xml><variables></variables><block type="control_forever" id="4Rmd8eEg(d`B2[snvIq^" x="42" y="55"></block></xml>';
      //workspace.clear();
      var xml = Blockly.Xml.textToDom(input);
      Blockly.Xml.clearWorkspaceAndLoadFromXml(xml,workspace);
      //Blockly.Xml.domToWorkspace(workspace, xml);
      //taChange();
    }


    // Disable the "Import from XML" button if the XML is invalid.
    // Preserve text between page reloads.
    function taChange() {
      var textarea = document.getElementById('importExport');
      if (sessionStorage) {
        sessionStorage.setItem('textarea', textarea.value);
      }
      var valid = true;
      try {
        Blockly.Xml.textToDom(textarea.value);
      } catch (e) {
        valid = false;
      }
      document.getElementById('import').disabled = !valid;
    }

    function logEvents(state) {
      var checkbox = document.getElementById('logCheck');
      checkbox.checked = state;
      if (sessionStorage) {
        sessionStorage.setItem('logEvents', state ? 'checked' : '');
      }
      if (state) {
        workspace.addChangeListener(logger);
      } else {
        workspace.removeChangeListener(logger);
      }
    }

    function logFlyoutEvents(state) {
      var checkbox = document.getElementById('logFlyoutCheck');
      checkbox.checked = state;
      if (sessionStorage) {
        sessionStorage.setItem('logFlyoutEvents', state ? 'checked' : '');
      }
      var flyoutWorkspace = (workspace.flyout_) ? workspace.flyout_.workspace_ :
        workspace.toolbox_.flyout_.workspace_;
      if (state) {
        flyoutWorkspace.addChangeListener(logger);
      } else {
        flyoutWorkspace.removeChangeListener(logger);
      }
    }

    function logger(e) {
      console.log(e);
    }

    function glowBlock() {
      if (Blockly.selected) {
        workspace.glowBlock(Blockly.selected.id, true);
      }
    }

    function unglowBlock() {
      if (Blockly.selected) {
        workspace.glowBlock(Blockly.selected.id, false);
      }
    }

    function glowStack() {
      if (Blockly.selected) {
        workspace.glowStack(Blockly.selected.id, true);
      }
    }

    function unglowStack() {
      if (Blockly.selected) {
        workspace.glowStack(Blockly.selected.id, false);
      }
    }

    function sprinkles(n) {
      var prototypes = [];
      var toolbox = workspace.options.languageTree;
      if (!toolbox) {
        console.error('Toolbox not found; add a toolbox element to the DOM.');
        return;
      }
      var blocks = toolbox.getElementsByTagName('block');
      for (var i = 0; i < n; i++) {
        var blockXML = blocks[Math.floor(Math.random() * blocks.length)];
        var block = Blockly.Xml.domToBlock(blockXML, workspace);
        block.initSvg();
        block.moveBy(
          Math.round(Math.random() * 450 + 40),
          Math.round(Math.random() * 600 + 40)
        );
      }
    }

    function spaghetti(n) {
      var xml = spaghettiXml;
      for(var i = 0; i < n; i++) {
        xml = xml.replace(/(<(statement|next)( name="SUBSTACK")?>)<\//g,
        '$1' + spaghettiXml + '</');
      }
      xml = '<xml xmlns="http://www.w3.org/1999/xhtml">' + xml + '</xml>';
      var dom = Blockly.Xml.textToDom(xml);
      console.time('Spaghetti domToWorkspace');
      Blockly.Xml.domToWorkspace(workspace, dom);
      console.timeEnd('Spaghetti domToWorkspace');
    }

    var spaghettiXml = [
      '  <block type="control_repeat">',
      '    <value name="TIMES">',
      '      <shadow type="math_whole_number">',
      '        <field name="NUM">10</field>',
      '      </shadow>',
      '    </value>',
      '    <statement name="SUBSTACK"></statement>',
      '    <next></next>',
      '  </block>'
    ].join('\n');

    function setSoundsEnabled(state) {
      var checkbox = document.getElementById('soundsEnabled');
      checkbox.checked = (state) ? 'checked' : '';
      if (sessionStorage) {
        sessionStorage.setItem('soundsEnabled', state);
      }
    }
    function fakeDrag(id, dx, dy, opt_workspace) {
      var ws = opt_workspace || Blockly.getMainWorkspace();
      var blockToDrag = ws.getBlockById(id);

      if (!blockToDrag) {
        fakeDragWrapper();
        return;
      }
      var blockTop = blockToDrag.svgGroup_.getBoundingClientRect().top;
      var blockLeft = blockToDrag.svgGroup_.getBoundingClientRect().left;

      // Click somewhere on the block.
      var mouseDownEvent = new MouseEvent('mousedown',
          {clientX: blockLeft + 5, clientY: blockTop + 5});
      blockToDrag.onMouseDown_(mouseDownEvent);

      // Throw in a move for good measure.
      setTimeout(
        function() {
          var mouseMoveEvent = new MouseEvent('mousemove',
              {clientX: blockLeft + dx,
              clientY: blockTop + dy});
          blockToDrag.onMouseMove_(mouseMoveEvent);

          // Drop at dx, dy.
          setTimeout(
            function() {
              var mouseUpEvent = new MouseEvent('mouseup',
                  {clientX: blockLeft + dx,
                  clientY: blockTop + dy});
              blockToDrag.onMouseUp_(mouseUpEvent);

              setTimeout(fakeDragWrapper, 100);
            }, 30);
        }, 30);
    }

    function fakeDragWrapper() {
      var dragInfo = fakeDragStack.pop();
      if (dragInfo) {
        fakeDrag(dragInfo.id, dragInfo.dx, dragInfo.dy, dragInfo.workspace);
      }
    }

    function fakeManyDrags() {
      var blockList = workspace.getAllBlocks();
      for (var i = 0; i < 2 * blockList.length; i++) {
        fakeDragStack.push(
          {
            id: blockList[Math.round(Math.random() * (blockList.length - 1))].id,
            // Move some blocks up and to the left, but mostly down and to the right.
            dx: Math.round((Math.random() - 0.25) * 200),
            dy: Math.round((Math.random() - 0.25) * 200),
            workspace: workspace
          });
      }
      fakeDragWrapper();
    }